import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hygf/http/file_transfer/upload_cap.dart';
import 'package:hygf/page/home/application/view.dart';
import 'package:hygf/util/location/location_gaode.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../../config/StyleConfig.dart';
import '../../../http/DioClient.dart';
import '../../../http/file_transfer/upload_request_option.dart';
import '../../../http/file_transfer/upload_result.dart';
import '../../../res/HDColors.dart';
import '../../../res/my_colors.dart';
import '../../../util/LoadingUtils.dart';
import '../../../util/location/location_manager.dart';
import '../../../view/FieldEditor.dart';
import '../../../view/camera/camera_page.dart';
import '../../../view/common_widget.dart';
import '../../../view/dialog/dialog_manager.dart';
import '../../../view/image_picker_widget.dart';
import '../../../view/image_preview_page.dart';
import 'logic.dart';

class BusinessPage extends StatelessWidget {
  BusinessPage({Key? key}) : super(key: key);

  final logic = Get.put(BusinessLogic());
  final state = Get.find<BusinessLogic>().state;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          LocationManager().clearTask();
          logic.closePage();
          return false;
        },
        child: Scaffold(
          appBar: AppBar(
              title: const Text("客户录入"),
              elevation: 0,
              backgroundColor: HDColors.green,
              leading: CommonWidget.getAppBarLeading(),
              actions: [
                GetBuilder<BusinessLogic>(builder: (logic) {
                  return Visibility(
                      visible:
                          state.readOnly != null && !(state.readOnly ?? false),
                      child: TextButton(
                          onPressed: () {},
                          child: const Text("暂存",
                              style: TextStyle(
                                  color: HDColors.white,
                                  fontSize: StyleConfig.fontContentSize16))));
                }),
              ]),
          body: GetBuilder<BusinessLogic>(builder: (logic) {
            return SingleChildScrollView(
                child: Column(children: buildBody(context)));
          }),
          bottomNavigationBar:
              state.readOnly ?? false ? const SizedBox() : const SizedBox(),
        ));
  }

  buildBody(BuildContext context) {
    return <Widget>[
      buildOcrWidget(context),
      Container(
        height: 8,
        width: double.infinity,
        color: const Color(0xffF8F8F8),
      ),
      buildListWidget(),
    ];
  }

  buildOcrWidget(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        GestureDetector(
          onTap: () async {
            if (state.idImgAvatar.isEmpty) {
              var result  = await _showActionSheet(context);
              // var result = await Get.to(CameraPage(
              //   cameraType: CameraType.IMAGE,
              // ));
              if (result != null && result is String) {
                state.idImgAvatar = result as String;
                final XFile photo = XFile(state.idImgAvatar);
                final Uint8List bytes = await photo.readAsBytes();
                String base64Image = base64Encode(bytes);
                logic.baiduOcr(base64Image);
                _uploadIdImg(true, state.idImgAvatar);
              }
            } else {
              ImagePickerData data = ImagePickerData(
                  state.idImgAvatar.split("/").last, state.idImgAvatar);
              Get.to(ImagePreviewPage(data: [data]));
            }
          },
          child: Stack(
            alignment: Alignment.center,
            children: [
              Container(
                  margin: EdgeInsets.fromLTRB(0, 30, 0, 30),
                  height: 80,
                  width: 120,
                  child: buildIdImgAvatarWidget()),
              Visibility(
                visible: state.idImgAvatar.isNotEmpty,
                  child: Positioned(
                    width: 40,
                    height:40,
                    right: 2,
                    top: 30,
                    child: GestureDetector(
                      onTap: () {
                        state.idImgAvatar = "";
                        state.customerBean.idNumberPositive = [];
                        logic.update();
                      },
                      child: Container(
                        color: Colors.transparent,
                        padding:
                        EdgeInsets.only(left: 16, bottom: 16),
                        child: Image.asset(
                            "assets/images/media_editor_asset_delete.webp"),
                      ),
                    ),
                  )

                 ),
              Text(
                '上传身份证头像面',
                style: TextStyle(
                    color: HDColors.black,
                    fontSize: StyleConfig.fontContentSize14),
              ),
            ],
          ),
        ),
        GestureDetector(
            onTap: () async {
              if (state.idImg.isEmpty) {
                var result  = await _showActionSheet(context);
                if (result != null && result is String) {
                  state.idImg = result;
                  logic.update();
                  _uploadIdImg(false, result);
                }
              } else {
                ImagePickerData data =
                    ImagePickerData(state.idImg.split("/").last, state.idImg);
                Get.to(ImagePreviewPage(data: [data]));
              }
            },
            child: Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  height: 80,
                  width: 120,
                  child: buildIdImgNegativeWidget(),
                ),
                Visibility(
                    visible: state.idImg.isNotEmpty,
                    child: Positioned(
                      width: 40,
                      height:40,
                      right: 2,
                      top: 0,
                      child: GestureDetector(
                        onTap: () {
                          state.idImg = "";
                          state.customerBean.idNumberNegative = [];
                          logic.update();
                        },
                        child: Container(
                          color: Colors.transparent,
                          padding:
                          EdgeInsets.only(left: 16, bottom: 16),
                          child: Image.asset(
                              "assets/images/media_editor_asset_delete.webp"),
                        ),
                      ),
                    )

                ),
                Text(
                  '上传身份证国徽面',
                  style: TextStyle(
                      color: HDColors.black,
                      fontSize: StyleConfig.fontContentSize14),
                ),
              ],
            )),
      ],
    );
  }

  buildListWidget() {
    return SingleChildScrollView(
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        FieldEditor(
            label: '姓名',
            hintText: '请输入姓名',
            contentTextAlign: TextAlign.end,
            initialValue: state.customerBean.customerName ?? "",
            showLine: false,
            controller: state.nameController
              ..text = state.customerBean.customerName ?? "",
            onChanged: (value) {
              state.customerBean.customerName = value;
            }),
        FieldEditor(
            label: '电话',
            hintText: '请输入手机号',
            contentTextAlign: TextAlign.end,
            showLine: false,
            initialValue: state.customerBean.phoneNumber,
            controller: state.phoneController
              ..text = state.customerBean.phoneNumber ?? "",
            onChanged: (value) {
              state.customerBean.phoneNumber = value;
            }),
        FieldEditor(
            label: '身份证号',
            hintText: '请输入身份证号',
            contentTextAlign: TextAlign.end,
            initialValue: state.customerBean.idNumber ?? "",
            showLine: false,
            controller: state.idNumController
              ..text = state.customerBean.idNumber ?? "",
            onChanged: (value) {
              state.customerBean.idNumber = value;
            }),
        FieldEditor(
            label: '银行账号',
            hintText: '请输入银行账号',
            initialValue: state.customerBean.bankCardNumber ?? "",
            contentTextAlign: TextAlign.end,
            showLine: false,
            controller: state.bankCardNumController
              ..text = state.customerBean.bankCardNumber ?? "",
            onChanged: (value) {
              state.customerBean.bankCardNumber = value;
            }),
        FieldEditor(
            label: '开户行名称',
            hintText: '请输入开户行名称',
            initialValue: state.customerBean.bankName ?? "",
            contentTextAlign: TextAlign.end,
            showLine: false,
            controller: state.bankName
              ..text = state.customerBean.bankName ?? "",
            onChanged: (value) {
              state.customerBean.bankName = value;
            }),
        Container(
          color: HDColors.white,
          child: Stack(children: [
            FieldEditor(
                label: '建站地址',
                hintText: '请输入建站地址',
                contentTextAlign: TextAlign.end,
                initialValue: state.customerBean.buildingAddress,
                rightIcon:
                    Icon(color: HDColors.blue, Icons.location_on_outlined),
                showLine: false,
                controller: state.locationController,
                onChanged: (value) {
                  state.customerBean.buildingAddress = value;
                }),
            Positioned(
              right: -10,
              top: 0,
              bottom: 0,
              child: TextButton(
                onPressed: () async {
                  LoadingUtils.showToast("开始获取当前定位");
                  var getLocation =
                      await LocationGaode().startLocation((location) => {});
                  if ((getLocation.address ?? "").isEmpty) {
                    LoadingUtils.showToast("定位失败,请重新定位");
                  } else {
                    LoadingUtils.showToast("定位:${getLocation.address}");
                    state.customerBean.buildingAddress = getLocation.address;
                    state.customerBean.longitude = getLocation.longitude;
                    state.customerBean.latitude = getLocation.latitude;
                    state.locationController.text =
                        state.customerBean.buildingAddress ?? "";
                    logic.update();
                  }
                },
                child: Container(
                  alignment: Alignment.centerRight,
                  height: 80,
                  width: 30,
                ),
              ),
            ),
          ]),
        ),
        Visibility(
          visible: (state.customerBean.longitude ?? "").isNotEmpty,
          child: BrnTextInputFormItem(
            title: '经度：${state.customerBean.latitude}',
            isRequire: false,
            isEdit: false,
            hint: "",
          ),
        ),
        Visibility(
          visible: (state.customerBean.latitude ?? "").isNotEmpty,
          child: BrnTextInputFormItem(
            title: '纬度：${state.customerBean.latitude}',
            isRequire: false,
            isEdit: false,
            hint: "",
          ),
        ),
        Row(
          children: <Widget>[
            SizedBox(
                width: 15
            ),
            Text("期数：",style: TextStyle(fontSize: 17),),
            BrnRadioButton(
              radioIndex: 0,
              isSelected: state.customerBean.period == 1,
              child: Padding(
                padding: EdgeInsets.only(left: 5),
                child: Text(
                    "1",style: TextStyle(fontSize: 17)
                ),
              ),
              onValueChangedAtIndex: (index, value) {
                state.customerBean.period = 1;
                logic.update();
              },
            ),
            SizedBox(
              width: 20,
            ),
            BrnRadioButton(
              radioIndex: 1,
              isSelected:  state.customerBean.period == 2,
              child: Padding(
                padding: EdgeInsets.only(left: 5),
                child: Text(
                    "2",style: TextStyle(fontSize: 17)
                ),
              ),
              onValueChangedAtIndex: (index, value) {
                state.customerBean.period = 2;
                logic.update();
              },
            )
          ],
        ),
        FieldEditor(
            label: '备注',
            hintText: '请输入备注信息',
            initialValue: state.customerBean.remarks ?? "",
            contentTextAlign: TextAlign.end,
            showLine: false,
            isRequired: false,
            controller: state.remarkController
              ..text = state.customerBean.remarks ?? "",
            onChanged: (value) {
              state.customerBean.remarks = value;
            }),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: Text('银行卡照片',
              style: TextStyle(color: HDColors.black, fontSize: 16)),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: ImagePickerWidget(controller: state.bankController),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: Text('房屋产权证明照片',
              style: TextStyle(color: HDColors.black, fontSize: 16)),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: ImagePickerWidget(controller: state.houseCerController),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: Text('正大门照片',
              style: TextStyle(color: HDColors.black, fontSize: 16)),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: ImagePickerWidget(controller: state.gatePhotoController),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child:
              Text('其他', style: TextStyle(color: HDColors.black, fontSize: 16)),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(13, 0, 20, 0),
          child: ImagePickerWidget(controller: state.otherController),
        ),
        getFooterButton()
      ]),
    );
  }

  getFooterButton() {
    return Container(
        decoration: const BoxDecoration(color: HDColors.white, boxShadow: [
          BoxShadow(
              color: HDColors.grayBg,
              offset: Offset(0, -2),
              blurRadius: 8,
              spreadRadius: 1)
        ]),
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            CommonWidget.buildBottomBtn("暂存", () {
              logic.submit(0);
            }),
            CommonWidget.buildBottomBtn("提交", () {
              logic.submit(1);
            }),
          ],
        ));
  }

  void handleOcrError() {
    print("识别错误:");
  }

  void handleJsonRes(String jsonRes) {
    print("handleJsonRes:${handleJsonRes}");
  }

  void handleStart(Uint8List imageBytes) {
    print("handleStart:${handleStart}");
  }

  buildIdImgAvatarWidget() {
    if (state.idImgAvatar.isEmpty) {
      return Image.asset(
        "assets/images/idcard_in.png",
        fit: BoxFit.fill,
      );
    } else if (state.idImgAvatar.startsWith("http://") ||
        state.idImgAvatar.startsWith("https://")) {
      // 如果地址以http或https开头 就认为他是网络地址
      return FadeInImage.assetNetwork(
        placeholder: "assets/images/image_picker_placehold.webp",
        image: state.idImgAvatar,
        fit: BoxFit.cover,
        imageErrorBuilder: (context, error, stackTrace) {
          return Image.asset("assets/images/image_picker_placehold.webp");
        },
      );
    } else {
      return Image.file(File(state.idImgAvatar), fit: BoxFit.cover);
    }
  }

  buildIdImgNegativeWidget() {
    if (state.idImg.isEmpty) {
      return Image.asset(
        "assets/images/idcard_con.png",
        fit: BoxFit.fill,
      );
    } else if (state.idImgAvatar.startsWith("http://") ||
        state.idImgAvatar.startsWith("https://")) {
      // 如果地址以http或https开头 就认为他是网络地址
      return FadeInImage.assetNetwork(
        placeholder: "assets/images/image_picker_placehold.webp",
        image: state.idImgAvatar,
        fit: BoxFit.cover,
        imageErrorBuilder: (context, error, stackTrace) {
          return Image.asset("assets/images/image_picker_placehold.webp");
        },
      );
    } else {
      return Image.file(File(state.idImg), fit: BoxFit.cover);
    }
  }

  _uploadIdImg(bool isAvatar, String filePath) async {
    List<BaseUploadRequestOption> files = [];
    files.add(FileUploadRequestOption(
        type: UploadFileType.media, filePath: filePath, keepFileName: true));
    await DioClient().uploadFiles(files, isAsync: false, hideLoading: true,
        progressListener: (response, i, t) {
      if (response?.isok != true) {
        LoadingUtils.showToast("上传失败");
      } else {
        LoadingUtils.showToast("上传成功");
        if (isAvatar) {
          state.customerBean.idNumberPositive = [];
          state.customerBean.idNumberPositive!
              .add((response?.data as UploadResult).id ?? 0);
        } else {
          state.customerBean.idNumberNegative = [];
          state.customerBean.idNumberNegative!
              .add((response?.data as UploadResult).id ?? 0);
        }
      }
    });
  }

  Future<String> _showActionSheet(BuildContext context) async {
    FocusScope.of(context).requestFocus(FocusNode());
    var map = await DialogManager.showActionSheet(
        items: [
          {"name": "拍照", "code": "photo"},
          {"name": "从相册选择", "code": "album"}
        ], title: "请选择");
    switch (map["code"] ?? "") {
      case "photo":
      // 拍照
        var result = await Get.to(CameraPage(
          cameraType: CameraType.IMAGE,
        ));
        return result;
      case "album":
        var result = await AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
              maxAssets: 1,
              themeColor: MyColors.accent,
              textDelegate: AssetPickerTextDelegate(),
              requestType: RequestType.image),
        );
        if (result != null && result.isNotEmpty) {
          List<ImagePickerData> req = [];
          for (var item in result) {
            File? file = await item.originFile;
            if (file != null) {
              return file.path;
            }
          }
        }
        break;
      default:
    }
    return "";
  }
}
